package com.liuwei.msmall.order.listener;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.liuwei.msmall.order.config.AlipayTemplate;
import com.liuwei.msmall.order.service.OrderService;
import com.liuwei.msmall.order.vo.PayAsyncVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @Classname PayedListener
 * @Description TODO
 * @Date 2020/8/5 4:34
 * @Created by 刘
 */
//监听支付宝异步通知支付结果信息
@Slf4j
@RestController
public class PayedListener {

    @Autowired
    AlipayTemplate alipayTemplate;
    @Autowired
    OrderService orderService;


    /**
     * 只要拿到支付宝给我们的异步通知，返回success，支付宝就不会再通知我们，（属于柔性事务中最大努力通知，保证数据一致性）
     * @param request
     * @return
     */
    @PostMapping("/payed/notify")//必须是post请求，详情查看支付宝开放平台
    public String handleAlipayed(PayAsyncVo vo, HttpServletRequest request) throws AlipayApiException, UnsupportedEncodingException {


        log.info("收到支付宝异步通知结果：{}", JSON.toJSON(vo));
        //1.验签
        //获取支付宝POST过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        Map<String,String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
//            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        //调用SDK验证签名
        boolean signVerified = AlipaySignature.rsaCheckV1(params, alipayTemplate.getAlipayPublicKey(), alipayTemplate.getCharset(), alipayTemplate.getSignType());
        if (signVerified){
            log.info("验签成功,处理支付结果中。。。");
            //2.处理支付结果
            String result = orderService.handlePayResult(vo);
            return result;
        }else {
            log.error("验证签名失败");
            return "error";
        }

    }

}
